import json, re
from ws_setting import logger, CUSTOM_OBJ_SESSION_ID_NAME

def obj_to_str(data):
    _data = data
    """
                convert to python obj from str to json
    """
    if not _data:
        return ""

    if type(_data) == dict or hasattr(_data, "__dict__"):
        #response is  customer object
        if hasattr(_data, "__dict__"):
            _data = _data.__dict__
        return json.dumps(_data, cls=ComplexEncoder)
    elif hasattr(_data, "__iter__") and type(_data) != str:
    #response is iterable
        return json.dumps(list(_data), cls=ComplexEncoder)
    else:
        #any else conver to str
        return str(_data)


def load_str(data):
    try:
        return json.loads(re.sub("'", "\"", data))
    except:
        return ""

from core.ws_response import WsObject

class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if type(obj) == set:
            obj = list(obj)

        if hasattr(obj, "__dict__"):
            obj_dict = obj.__dict__.copy()
            if isinstance(obj, WsObject):
                #remove session id attr
                if CUSTOM_OBJ_SESSION_ID_NAME in obj_dict:
                    del obj_dict[CUSTOM_OBJ_SESSION_ID_NAME]
            return obj_dict
        return json.JSONEncoder.default(self, obj)
